package com.wzy.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.wzy.ucenter.mapper.XcUserMapper;
import com.wzy.ucenter.model.dto.AuthParamsDto;
import com.wzy.ucenter.model.dto.XcUserExt;
import com.wzy.ucenter.model.po.XcMenu;
import com.wzy.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author wzy
 * @Date 2024/1/29 11:01
 * @description: 实现UserDetailsService 接口查询数据库得到用户信息返回UserDetails 类型的用户信息
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    private XcUserMapper xcUserMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s,AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException(e);
        }
        //认证方法 password、wx....
        String authType = authParamsDto.getAuthType();
        AuthService bean = applicationContext.getBean(authType + "_authService", AuthService.class);
        XcUserExt userExt = bean.execute(authParamsDto);
        return getUserPrincipal(userExt);
    }

    /**
     * 封装查询出的用户信息成UserDetails
     * @param user 用户
     * @return
     */
    private UserDetails getUserPrincipal(XcUserExt user) {
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities;
        //查询用户权限
        List<XcMenu> xcMenus = xcUserMapper.selectUserPermissionByUserId(user.getId());//权限列表
        ArrayList<String> xcMenuArrayList = new ArrayList<>();
        if(!xcMenus.isEmpty()){
            for (XcMenu xcMenu : xcMenus) {
                xcMenuArrayList.add(xcMenu.getCode());
            }
        }
        user.setPermissions(xcMenuArrayList);
        String[] permission = xcMenuArrayList.toArray(new String[0]);

        String password = user.getPassword();
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(user);
        //创建UserDetails对象
        UserDetails userDetails = User.withUsername(userString).password(password ).authorities(permission).build();
        return userDetails;

    }
}
